package com.mdlib.helper.api;

import android.app.Activity;

import com.ljlib.core.dialog.HelperWaitDialog;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.event.ImageID;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者：HQY on 16/12/10 09:41
 * 邮箱：hqy_xz@126.com
 */

public class MDUploadPic extends MDPresenter {


    public static void uploadPic(final List<String> namelist, Activity activity,String type) {
        final HelperWaitDialog helperWaitDialog = new HelperWaitDialog(activity, false);
        helperWaitDialog.show();

        RequestBody imgExtBody = RequestBody.create(MediaType.parse("multipart/form-data"), "jpg");

        RequestBody uploadTypeBody = RequestBody.create(MediaType.parse("multipart/form-data"), type);

        RequestBody sessionBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                AccountModel.getInstance().getSessionId());
        List<MultipartBody.Part> partList = new ArrayList<>();
        if (namelist.size() > 0) {
            for (int i = 0; i < namelist.size(); i++) {
                File file = new File(namelist.get(i));
                RequestBody requestImgFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part ImageFilebody = MultipartBody.Part.createFormData("img" + i, file.getName(), requestImgFile);
                partList.add(ImageFilebody);
            }
        }

        addSubscribe(DataManager.getInstance().getSpecialApi()
                .uploadImage(partList, imgExtBody, uploadTypeBody, sessionBody)
                .compose(RxHelper.<ArrayList<String>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<String>>() {
                    @Override
                    protected void onSucc(ArrayList<String> upImages) {
                        EventBus.getDefault().post(new ImageID(upImages, namelist));
                        helperWaitDialog.close();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                        helperWaitDialog.close();
                    }
                }));

    }


    @Override
    public void onDestory() {
        unSubscribe();
    }
}
